﻿using System;

namespace Basmus.Conel
{
    public class NullableBinder : IBinder
    {
        public Binding Bind(Type containerType)
        {
            var elementType = Nullable.GetUnderlyingType(containerType);
            if (elementType != null)
            {
                return CreateNullableGenericBinding(elementType);
            }
            return null;
        }

        public Binding Bind(Type containerType, Type elementType)
        {
            if (elementType == Nullable.GetUnderlyingType(containerType))
            {
                return CreateNullableGenericBinding(elementType);
            }
            return null;
        }
        private static Binding CreateNullableGenericBinding(Type elementType)
        {
            var bindingType = typeof(NullableBinding<>).MakeGenericType(elementType);
            var binding = (Binding)Activator.CreateInstance(bindingType);
            return binding;
        }
    }
}
